<style>
    .wrap {
        margin: 5px 5px 0 0
    }
</style>
<template>
    <mavon-editor class="wrap" @change="onChange"
                  @imgAdd="onImgAdd" @imgDel="onImgDel"
                  :editable="editable" v-model="content">
    </mavon-editor>
</template>
<script>
    export default {
        props: {
            value: {
                type: String,
                default: ''
            },
            editable: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                content: (() => {
                    return this.value
                })(),
                img_file: {},
                contentInit: false
            }
        },
        watch: {
          value(value,oldValue) {
              if (!this.contentInit) {
                  this.contentInit = true
                  this.content = value
              }
          }
        },
        methods: {
            uploadImg(file){
                let formData = new FormData();
                formData.append("file", file)
                return this.$http.post("/resource", formData).then((res) => {
                    return res.data
                }).catch((err) => {
                    return Promise.reject(err)
                })
            },
            onImgAdd(filename, file) {
                this.uploadImg(file).then((img) => {
                    console.log('上传成功: ', img)
                    this.img_file[filename] = img
                    this.content = this.content.replace(filename, img.url)
                }).catch((err) => {
                    console.warn("上传失败：", err)
                })
            },
            onImgDel(filename) {
                if (this.img_file[filename]) {
                    this.$http.delete(`/resource/${this.img_file[filename].id}`).then((resp) => {
                        console.log(`${this.img_file[filename]} 删除成功`)
                        delete this.img_file[filename]
                    }).catch(console.warn.bind(console))
                }
            },
            onChange(value, render) {
                this.$emit('content-change', value)
            }
        }
    }
</script>
